package com.base.core.context.utils.dingtalk;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;

import com.gitee.magic.core.exception.ApplicationException;
import com.gitee.magic.core.json.JsonObject;
import com.gitee.magic.framework.base.rest.HttpMultipartForm;
import com.gitee.magic.framework.base.rest.HttpMultipartForm.MultipartForm;
import com.gitee.magic.framework.base.rest.HttpRequest;
import com.gitee.magic.framework.base.rest.HttpWrapper;
import com.gitee.magic.framework.base.rest.RequestMethodEnum;

/**
 * <pre>
 * 登录钉钉开发者平台
 * 创建企业内部应用可获取appkey、appsecret
 * 在开发管理中配置服务器出口IP
 * chatId获取方法
 * 1、打开 https://open-dev.dingtalk.com/apiExplorer?spm=ding_open_doc.document.0.0.afb839b7W85NCP#/jsapi?api=biz.chat.chooseConversationByCorpId 选择所属企业后扫码
 * 2、搜索 biz.chat.chooseConversationByCorpId根据corpId选择会话(2.6新增)
 * 3、corpId可登录钉钉开发者后台查看、filterNotOwnerGroup可以设置为false表示只看自己创建的群
 * 4、点击执行在APP上选择对应的群就可以看到chatId
 * </pre>
 * 
 * @author start
 *
 */
public class DingTalkService {

	private String url;
	
	private String appkey;
	private String appsecret;

	public DingTalkService(String appKey,String appSecret) {
		this.url="https://oapi.dingtalk.com";
		this.appkey=appKey;
		this.appsecret=appSecret;
	}
	
	public String getAccessToken() {
		HttpRequest request = new HttpRequest(this.url+"/gettoken", RequestMethodEnum.GET);
		request.setUrlParam("appkey", appkey);
		request.setUrlParam("appsecret", appsecret);
		HttpWrapper wrapper = new HttpWrapper();
		String content = wrapper.start(request);
		JsonObject json = getResponseJson(content);
		return json.getString("access_token");
	}

	public String sendText(String accessToken, String content, String chatId) {
		JsonObject msgTypeJson=new JsonObject();
		msgTypeJson.put("content", content);
		return send(accessToken,chatId,"text",msgTypeJson);
	}
	
	public String sendFile(String accessToken, String fileName,String content, String chatId) {
		String fileType="file";
		InputStream inputStream = new ByteArrayInputStream(content.getBytes());
		String mediaId=getMediaId(accessToken,fileType,fileName + System.currentTimeMillis() + ".txt",inputStream);
		JsonObject msgTypeJson=new JsonObject();
		msgTypeJson.put("media_id", mediaId);
		return send(accessToken,chatId,fileType,msgTypeJson);
	}
	
	public String sendImage(String accessToken, String fileName,InputStream inputStream, String chatId) {
		String fileType="image";
		String mediaId=getMediaId(accessToken,fileType,fileName,inputStream);
		JsonObject msgTypeJson=new JsonObject();
		msgTypeJson.put("media_id", mediaId);
		return send(accessToken,chatId,fileType,msgTypeJson);
	}
	
	public String send(String accessToken, String chatId,String msgtype, JsonObject msgTypeJson) {
		JsonObject msgJson=new JsonObject();
		msgJson.put("msgtype", msgtype);
		msgJson.put(msgtype, msgTypeJson);
		JsonObject body=new JsonObject();
		body.put("chatid", chatId);
		body.put("msg", msgJson);

		HttpRequest request = new HttpRequest(this.url+"/chat/send");
		request.setHeader(HttpWrapper.CONTENTTYPE, HttpWrapper.CONTENTTYPE_JSON);
		request.setUrlParam("access_token", accessToken);
		request.setBodyContent(body.toString());
		HttpWrapper wrapper = new HttpWrapper();
		String content1=wrapper.start(request);
		JsonObject json = getResponseJson(content1);
		return json.getString("messageId");
	}
	
	/**
	 * 	
	 * @param accessToken
	 * @param fileType
	 * @param fileName
	 * @param inputStream
	 * @return
	 */
	public String getMediaId(String accessToken,String fileType,String fileName,InputStream inputStream) {
		HttpRequest request = new HttpRequest(this.url+"/media/upload");
		request.setUrlParam("access_token", accessToken);
		HttpWrapper wrapper = new HttpWrapper();
		HttpURLConnection connection=wrapper.requestConnect(request);
		Map<String,String> formParams=new HashMap<>();
//		image：图片，图片最大20MB。支持上传jpg、gif、png、bmp格式。
//		voice：语音，语音文件最大2MB。支持上传amr、mp3、wav格式。
//		video：视频，视频最大20MB。支持上传mp4格式。
//		file：普通文件，最大20MB。支持上传doc、docx、xls、xlsx、ppt、pptx、zip、pdf、rar格式。
		formParams.put("type", fileType);
		Map<String,MultipartForm> multipartParams=new HashMap<>();
		multipartParams.put(fileName, new MultipartForm() {

			@Override
			public String getContentName() {
				return "media";
			}
			
			@Override
			public InputStream getInputStream() {
				return inputStream;
			}
			
		});
		HttpMultipartForm.multipartFormData(connection, formParams, multipartParams);
		String content = wrapper.start(request,connection);
		JsonObject json = getResponseJson(content);
		return json.getString("media_id");
	}
	
	private JsonObject getResponseJson(String content) {
		JsonObject json = new JsonObject(content);
		if (json.getInt("errcode") != 0) {
			throw new ApplicationException(content);
		}
		return json;
	}

	public static void main(String[] args) throws Exception {
		String ak = "dinggftj0gieanb240sx";
		String as = "b4Jc7mU8JyX7qQM5yM5yKc_Diit4KrPmuJUv6esm26m70Yar2LImyDYBoFXLppn_";
		DingTalkService dt = new DingTalkService(ak,as);
		String accessToken = dt.getAccessToken();
		System.out.println(accessToken);
		String defaultChatId = "chat01ffd4ce45dfc8d7d2066bb683ab807a";
//		dt.sendText(accessToken, "这是测试内容", defaultChatId);
		dt.sendFile(accessToken, "Bridge", "这是测试内容",defaultChatId);
//		dt.sendImage(accessToken, "图片", new FileInputStream(new File("/Users/mac/Desktop/20240711212323.jpg")), defaultChatId);
	}

}
